Day 15 - Regular expressions - Anchors
49
$ grep -E "dog" examples.txt
dog
dog
corn dog
which returns all lines with the string dog somewhere in them. If you run
$ cat examples.txt | grep -E "^dog"
dog
dog
you will notice that the last line is not there, because the ^ anchors the string dog to the beginning
of the line. Conversely, if you run
$ cat examples.txt | grep -E "dog$"
dog
dog
corn dog
you will get the same result of the first run, as all those dog strings are at the end of the line.
You can also combine the two in a single regular expression if you need to anchor something at the
beginning and something else at the end
$ cat examples.txt | grep -E "^co.*og$"
corn dog
From the last example, it follows that if you want to match the exact content of a line you just need
to surround the search pattern with anchors
$ cat examples.txt | grep -E "^hog$"
hog
If you try the last example without either the ^ or the $ you will see that the result changes as the
pattern matches only part of the line.
Exercises
Exercise 15.01
Match every line of examples.txt that ends with an upper case letter and a number (in this order)
Go to solution